<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 以get方式提交数据时,会将参数数据队列提交到action所指的url中(数据拼接在url之后用?分隔) -->
    <form onsubmit="return false">
        <div>
            <label for="user">用户名:</label>
            <input name="user" type="text">
            <span class="user_span"></span>
        </div>
        <div>
            <label for="pwd">密&emsp;码:</label>
            <input name="pwd" type="text">
            <span class="pwd_span"></span>
        </div>
        <div>
            <button id="btn">注册</button>
            <input type="reset">
        </div>
    </form>
</body>
<script>
    var userInp = document.getElementsByName("user")[0];
    var pwdInp = document.getElementsByName("pwd")[0];

    var btn = document.getElementById("btn");


    btn.onclick = function () {

        var user = userInp.value;
        var pwd = pwdInp.value;

        var req = new XMLHttpRequest();  // 0

        // 以post方式提交数据时 ,是通过HTTP post机制，将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址。用户看不到这个过程。
        // (1) 将参数数据 作为send()第一参数传入到send()中
        // (2) 配置请求头 =>  以post方式提交数据时 ,是通过HTTP post机制,将数据放置在HTML HEADER内一起传送到url
        //  req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        req.open("post", "../php/post.php", true);  // 1
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        req.send(`user=${user}&pwd=${pwd}`);  // 1

        req.onreadystatechange = function () {
            console.log("readyState", req.readyState);  // 2 3 4
            if (req.readyState == 4 && req.status == 200) {
                console.log(req.responseText);

                // 后端返回的响应数据 可以是 txt/html/xml/json数据(json字符串)
                // var result = JSON.parse(req.responseText);
                // console.log(result);
            }
        }
    }

</script>

</html>